package com.mamingchao.concurrent.fromHashtableToHCM;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by mamingchao on 2020/11/3.
 */
public class ConcurrentHashMapTest {

    static Thread[] threads = new Thread[Constants.THREAD_NUM];

    static Map<UUID,UUID> map = new ConcurrentHashMap<>();
    static UUID[] key = new UUID[Constants.COUNT];
    static UUID[] value = new UUID[Constants.COUNT];

    static {
        for (int i = 0; i < Constants.COUNT; i++) {
            key[i] = UUID.randomUUID();
            value[i] = UUID.randomUUID();
        }
    }

    public static void main(String[] args) {
        int start = 0;
        for (int i = 0; i < Constants.THREAD_NUM; i++) {

            int finalStart = start;
            if (finalStart == 1000000){
                System.out.println("wait");
            }
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = finalStart; j < finalStart + Constants.COUNT/Constants.THREAD_NUM; j++) {
                        map.put(key[j],value[j]);
                    }
                }
            });

            threads[i]=t;
            start = start + Constants.COUNT/Constants.THREAD_NUM;
        }

        long startTime = System.currentTimeMillis();
        for (Thread thread:threads){
            thread.start();
        }

        for (Thread thread:threads){
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long endTime = System.currentTimeMillis();

        System.out.println("Hashtable put data cost " + (endTime-startTime));
        System.out.println("map size is " + map.size());

        
        //-------------------------------
        
        startTime = System.currentTimeMillis();
        for (int i = 0; i < Constants.THREAD_NUM; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j <1000000 ; j++) {
                    map.get(key[10]);
                }

            });
        }

        for (Thread thread:threads){
            thread.start();
        }

        for (Thread thread:threads){
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        endTime = System.currentTimeMillis();

        System.out.println("Hashtable get data cost " + (endTime-startTime));
    }
}
